﻿/*  -------------------------------------------------
    This file is part of the SchoolTube Live Platform
    Copyright © 2009 SchoolTube, LLC
    
    Licensed under the GNU General Public License v3
    http://www.gnu.org/licenses/gpl.html
    
    http://code.google.com/p/schooltubelive/
    ------------------------------------------------- */

import com.quantcast.Quantcast;
import com.schooltube.*;

import flash.display.*;
import flash.events.*;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.ui.ContextMenu;
import flash.ui.ContextMenuItem;

import mx.core.Application;
import mx.events.SliderEvent;

private var appVer:String	= "0.1.8";
private var appURL:String	= "rtmp://fmsedge.schooltube.com/stlive/default";
private var qcPubId:String	= "p-398H0AJ3g8Eq-";

private var nc:NetConnection;
private var ns:NetStream;
private var videoInfo:Object;
public  var currentStream:String;

private var isMuted:Boolean = false;
private var currentVolume:Number = 0.5;
private var vid:Video;
private var isPlaying:Boolean = false;
private var state:Number = 0;
private var isFullScreen:Boolean = false;
private var userName:String;
private var vidStats:SharedObject;
private var qc:Quantcast;

public function initApp():void {
	try {
		vid = new Video();
		videoInfo = new Object();
	} catch(e:Error){ trace("Video error");}
	
	videoContainer.addChild(vid);
	
	systemManager.stage.addEventListener(FullScreenEvent.FULL_SCREEN, doFullScreen);
	systemManager.stage.addEventListener(Event.RESIZE, resizeHandler);
	systemManager.stage.scaleMode = 'noScale';
	systemManager.stage.align = 'TL';
	Security.allowDomain(Security.LOCAL_WITH_NETWORK);
	
	volumeSlider.value = 0.5;
	
	vid.smoothing = true;
	
	var menuVersion:ContextMenuItem = new ContextMenuItem("SchoolTube Live Viewer - v" + appVer);
	menuVersion.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handleMenuClick);
	
	var menuCopyright:ContextMenuItem = new ContextMenuItem("Copyright © 2009 SchoolTube, LLC");
	menuCopyright.separatorBefore = true;
	menuCopyright.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handleMenuClick);
	
	var customContextMenu:ContextMenu = new ContextMenu();
	customContextMenu.hideBuiltInItems();
	customContextMenu.customItems.push(menuVersion, menuCopyright);
	
	mx.core.Application.application.contextMenu = customContextMenu;
	
	if (mx.core.Application.application.parameters.sid == undefined) {
		mx.core.Application.application.parameters.sid = "live";
	}
	
	if (mx.core.Application.application.parameters.sid != undefined) {
		currentStream = mx.core.Application.application.parameters.sid.toLowerCase();
		
		playVideo();
		
		try{
			qc = new Quantcast({publisherId: qcPubId, videoId: currentStream, title: currentStream, media:"video"}, null);
		} catch(e:Error){ trace("Quantcast error");}

	} else {
		currentStream = null;
		enableDisableControls(false);
	}
	
	WFInit();

}

private function handleMenuClick(event:ContextMenuEvent):void {
	gotoURL("http://www.schooltube.com/live");
}

private function gotoURL(URL:String, Target:String = '_blank'):void {
	var URLReq:URLRequest = new URLRequest(URL);
	navigateToURL(URLReq, Target);
}

private function handlePlayPause():void {
	if (isPlaying) {
		ns.pause();
		isPlaying = false;
		btnPlayPause.styleName = "playButton";
		btnPlayPause.toolTip = "Play";
		qc.paused();
	} else {
		ns.resume();
		isPlaying = true;
		btnPlayPause.styleName = "pauseButton";
		btnPlayPause.toolTip = "Pause";
		qc.played();
	}
}

private function playVideo():void {
	if (nc) {
		nc.close();
	}
	nc = new NetConnection();
	nc.client = this;
	nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
	nc.proxyType = "HTTP";
	nc.connect(appURL, false);
}

public function close():void {}
public function onBWDone():void {}

private function resizeHandler(event:Event):void {
	initScreen(stage.stageHeight, stage.stageWidth);
}

private function netStatusHandler(event:NetStatusEvent):void {
	var info:Object = event.info;

	switch (info.code) {
		case "NetConnection.Connect.Success":
			ns = new NetStream(nc);
			var nsClient:Object = new Object();
			nsClient.onMetaData = onMetaData;
			vid.attachNetStream(ns);
			ns.client = nsClient;
			ns.play(currentStream);
			isPlaying = true;
			btnPlayPause.styleName = "pauseButton";
			btnPlayPause.toolTip = "Pause";
			nc.call('addViewCount', null, currentStream);
			qc.played();
			try{
				vidStats = SharedObject.getRemote('appSO/' + currentStream, nc.uri, true);
				vidStats.connect(nc);
				vidStats.addEventListener(SyncEvent.SYNC, vidStatsSyncHandler);
				vidStats.addEventListener(NetStatusEvent.NET_STATUS, vidStatsNetHandler);
			}catch(err:Error){trace("Error : " + err.message);}
		break;
		
		case "NetConnection.Connect.Rejected":
			isPlaying = false;
			btnPlayPause.styleName = "playButton";
			btnPlayPause.toolTip = "Play";
			vid.clear();
		break;
		
		case "NetConnection.Connect.Failed":
			btnPlayPause.styleName = "playButton";
			btnPlayPause.toolTip = "Play";
			isPlaying = false;
			vid.clear();
		break;
		
		case "NetConnection.Connect.Closed":
			btnPlayPause.styleName = "playButton";
			btnPlayPause.toolTip = "Play";
			isPlaying = false;
			vid.clear();
		break;
	}
}

private function vidStatsNetHandler(event:NetStatusEvent):void {
	trace(event.info);
}

private function enableDisableControls(val:Boolean):void {
		btnPlayPause.enabled = val;
		btnPlayPause.useHandCursor = val;
		volumeSlider.enabled = val;
		volumeSlider.useHandCursor = val;
		btnVolume.enabled = val;
		btnVolume.useHandCursor = val;
		btnFullscreen.enabled = val;
		btnFullscreen.useHandCursor = val;
}

private function vidStatsSyncHandler(event:SyncEvent):void {
	if (vidStats.data.isLive == 0) {
		btnPlayPause.styleName = "playButton";
		btnPlayPause.toolTip = "Play";
		isPlaying = false;
		enableDisableControls(false);
		lblViewers.text = vidStats.data.streamName + ' - Not Live';
		vid.visible = false;
		qc.paused();
		return;
	} else if (vidStats.data.isLive == 1) {
		btnPlayPause.styleName = "pauseButton";
		btnPlayPause.toolTip = "Pause";
		isPlaying = true;
		enableDisableControls(true);
		vid.visible = true;
		qc.played();
	}
	if (vidStats.data.streamName && vidStats.data.totalViewerCount) {
		lblViewers.text = vidStats.data.streamName + ' - ' + vidStats.data.totalViewerCount.toString() + ' viewers';
	}
}

public function onMetaData(item:Object):void {
	videoInfo.width = item.width;
	videoInfo.height = item.height;
	initScreen(stage.stageHeight, stage.stageWidth);
}

private function showVolume(val:String):String {
	return (""+Math.round(Number(val)*100)+"");
}

private function changeVolume(event:SliderEvent):void {
	if(!isPlaying)
		return;
		
	currentVolume = event.value;
	var sndTransform:SoundTransform = new SoundTransform(event.value);
	ns.soundTransform = sndTransform;
	if(isMuted){
		doMute();
	}
}

private function doMute():void{
	if(!isPlaying) 
		return;
	
	if(!isMuted){
		var sndTransform:SoundTransform = new SoundTransform(0);
		ns.soundTransform = sndTransform;
   		isMuted=true;
   		btnVolume.toolTip = "Unmute";
   		btnVolume.styleName="muteButtonOn";
   	}else{
		var sndTransfrm:SoundTransform = new SoundTransform(currentVolume);
		ns.soundTransform = sndTransfrm;
   		isMuted=false;
   		btnVolume.toolTip = "Mute";
   		btnVolume.styleName="muteButton";
	}
}

private function resizeVideoPlayer(height:Number, width:Number):void {
	//Calculate aspect ratio
	var newWidth:Number = (videoInfo.width * height / videoInfo.height);
	var newHeight:Number = (videoInfo.height * width / videoInfo.width);
	if (newHeight < height) {
		vid.width = width;
		vid.height = newHeight;
	} else if (newWidth < width) {
		vid.width = newWidth;
		vid.height = height;
	} else {
		vid.width = width;
		vid.height = height;
	}
	
	//Center video player
	vid.x = Math.round((width - vid.width) / 2);
	vid.y = Math.round((height - vid.height) /2);
}

public function initScreen(height:Number, width:Number):void {
	if (videoInfo.width != undefined && videoInfo.height != undefined) {
		resizeVideoPlayer(height - 22, width);
	}
}

public function doFullScreen(e:FullScreenEvent) : void{
	try{
		if(e.fullScreen){
			isFullScreen = true;
		}
		else{
			isFullScreen = false;
		} 
		
		initScreen(stage.stageHeight, stage.stageWidth);
		
	}catch(err:Error){
	trace("Error : " + err.message);
	}
}

private function fullScreenHandler() : void{
		try{
			stage.displayState = (stage.displayState == StageDisplayState.FULL_SCREEN) ?
						StageDisplayState.NORMAL : StageDisplayState.FULL_SCREEN;
		}catch(err:Error){
			trace("Security Error : Full screen not allowed");
		}
		
		return;	
}